﻿namespace SalaryTool.Service
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Xml.Serialization;
    using SalaryTool.Service.Models;

    public class EmployeeFileDataSource : IEmployeeDataSource
    {
        private readonly string employeeDataFilePath;

        public EmployeeFileDataSource(string employeeDataFilePath)
        {
            this.employeeDataFilePath = employeeDataFilePath;
        }

        public IList<Employee> GetEmployees()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Employee>));

            using (StreamReader reader = new StreamReader(this.employeeDataFilePath))
            {
                List<Employee> employees = serializer.Deserialize(reader) as List<Employee>;

                return employees;
            }
        }

        public void UpdateMarketMultiplier(int id, int marketMultiplier)
        {
            IList<Employee> employees = this.GetEmployees();

            Employee employeeToUpdate = employees.FirstOrDefault<Employee>(e => e.Id == id);

            if (employeeToUpdate == null)
            {
                return;
            }

            employeeToUpdate.MarketPercentageMultiplier = marketMultiplier;

            this.WriteEmployeesToFile(employees as List<Employee>);
        }

        private void WriteEmployeesToFile(List<Employee> employees)
        {
            using (StreamWriter outfile = new StreamWriter(this.employeeDataFilePath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Employee>));

                serializer.Serialize(outfile, employees);
            }
        }
    }
}